from __future__ import division
import cv2
import numpy as np
from numpy import random
import math
from sklearn.utils import shuffle
import matplotlib.pyplot as plt

def rotate_bound(image, angle, borderValue=0, borderMode=None):
    # grab the dimensions of the image and then determine the
    # center
    h, w = image.shape[:2]

    (cX, cY) = (w // 2, h // 2)

    M = cv2.getRotationMatrix2D((cX, cY), angle, 1.0)
    cos = np.abs(M[0, 0])
    sin = np.abs(M[0, 1])

    # compute the new bounding dimensions of the image
    nW = int((h * sin) + (w * cos))
    nH = int((h * cos) + (w * sin))

    # adjust the rotation matrix to take into account translation
    M[0, 2] += (nW / 2) - cX
    M[1, 2] += (nH / 2) - cY

    if borderMode is None:
        rotated = cv2.warpAffine(image, M, (nW, nH), borderValue=borderValue, borderMode=0)
    else:
        rotated = cv2.warpAffine(image, M, (nW, nH),borderValue=borderValue, borderMode=borderMode)

    return rotated


def rotate_nobound(image, angle,borderValue=0, borderMode=None):
    (h, w) = image.shape[:2]


    # if the center is None, initialize it as the center of
    # the image
    center = (w // 2, h // 2)

    # perform the rotation
    M = cv2.getRotationMatrix2D(center, angle, 1.)
    if borderMode is None:
        rotated = cv2.warpAffine(image, M, (w, h), borderValue=borderValue, borderMode=0)
    else:
        rotated = cv2.warpAffine(image, M, (w, h), borderValue=borderValue, borderMode=borderMode)

    return rotated

def fixed_crop(src, x0, y0, w, h, size=None):
    out = src[y0:y0 + h, x0:x0 + w]
    if size is not None and (w, h) != size:
        out = cv2.resize(out, (size[0], size[1]), interpolation=cv2.INTER_CUBIC)
    return out
def scale_down(src_size, size):
    w, h = size
    sw, sh = src_size
    if sh < h:
        w, h = float(w * sh) / h, sh
    if sw < w:
        w, h = sw, float(h * sw) / w
    return int(w), int(h)

def center_crop(src, size):
    h, w = src.shape[0:2]
    new_w, new_h = scale_down((w, h), size)

    x0 = int((w - new_w) / 2)
    y0 = int((h - new_h) / 2)

    out = fixed_crop(src, x0, y0, new_w, new_h, size)
    return out


def scale_down2(src_size, size, xmin, xmax, ymin, ymax):
    w, h = size
    sw, sh = ymax-ymin, src_size[1]- xmin
    if sh < h:
        w, h = float(w * sh) / h, sh
    if sw < w:
        w, h = sw, float(h * sw) / w
    return int(w), int(h)